package com.three.box.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.three.box.R
import com.three.box.base.BaseActivity
import com.three.box.databinding.ActivityRecordInfoBinding
import com.three.box.entity.ApiResult
import com.three.box.entity.BoxHistory
import com.three.box.entity.BoxRecord
import com.three.box.entity.Product
import com.three.box.network.kt.ApiServiceFactory
import com.three.box.network.kt.AppApiService
import com.three.box.network.kt.AppHost
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class RecordInfoActivity : BaseActivity() {

    companion object {
        const val TAG = "RecordInfoActivity"
    }

    private lateinit var binding: ActivityRecordInfoBinding

    private var boxRecord: BoxRecord? = null
    private var recordId = -1

    override fun onCreate(savedInstanceState: Bundle?) {
        binding = ActivityRecordInfoBinding.inflate(layoutInflater)
        setStatusBar()
        super.onCreate(savedInstanceState)

        recordId = intent.getIntExtra("record_id", -1)

        initView()

        orderInfo()
    }

    override fun getLayoutView() = binding.root

    private fun initView() {
        binding.topLayout.visibility = View.INVISIBLE
        binding.recyclerView.visibility = View.INVISIBLE
        binding.backIv.setOnClickListener { finish() }
        binding.confirmBtn.setOnClickListener {
            val boxHistories = boxRecord?.boxProductHistoryInfo ?: listOf()
            val productList = ArrayList<Product>()
            boxHistories.forEach { boxHistory ->
                productList.add(Product(
                    productId = boxHistory.productId,
                    productName = boxHistory.productInfo.name,
                    productDesc = boxHistory.productInfo.desc,
                    productModelId = boxHistory.productModelId,
                    number = boxHistory.number,
                    groupId = boxHistory.groupId,
                    groupName = boxHistory.groupName,
                    productModelName = boxHistory.productModelName
                ))
            }
            setResult(RESULT_OK, Intent().apply {
                putParcelableArrayListExtra("product_list", productList)
            })
            finish()
        }
    }

    private fun initValues() {
        binding.topLayout.visibility = View.VISIBLE
        binding.recyclerView.visibility = View.VISIBLE
        binding.operatorTv.text = getString(R.string.format_operate_name, boxRecord?.userInfo?.username)
        binding.operatorTypeTv.text = getString(R.string.format_operate_type, boxRecord?.operateTypeInfo?.name ?: "无")
        binding.operateTimeTv.text = getString(R.string.format_operate_time, boxRecord?.time)
        binding.noteTv.text = getString(R.string.format_note, (boxRecord?.notes ?: "无"))

        val list = boxRecord?.boxProductHistoryInfo
        val historyAdapter = HistoryAdapter()
        with(binding.recyclerView) {
            layoutManager = LinearLayoutManager(context).apply { orientation = androidx.recyclerview.widget.RecyclerView.VERTICAL }
            addItemDecoration(DividerItemDecoration(this@RecordInfoActivity, DividerItemDecoration.VERTICAL))
            adapter = historyAdapter
        }
        historyAdapter.submitList(list)
    }

    inner class HistoryAdapter : BaseQuickAdapter<BoxHistory, QuickViewHolder>() {
        override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): QuickViewHolder {
            // 返回一个 ViewHolder
            return QuickViewHolder(R.layout.item_record_info, parent)
        }

        override fun onBindViewHolder(holder: QuickViewHolder, position: Int, item: BoxHistory?) {
            holder.setText(R.id.name_tv, getString(R.string.format_name, item?.productDesc))
            holder.setText(R.id.model_tv, getString(R.string.format_model, item?.productModelName))
            holder.setText(R.id.group_tv, getString(R.string.format_group, item?.groupName))
            holder.setText(R.id.number_tv, getString(R.string.format_number, item?.number))
        }
    }

    private val service = ApiServiceFactory.createAPIService(AppHost.AppApi, AppApiService::class.java)
    private fun orderInfo() {
        val call = service.orderInfo(recordId)
        call.enqueue(object : Callback<ApiResult<BoxRecord>> {
            override fun onResponse(
                call: Call<ApiResult<BoxRecord>>,
                response: Response<ApiResult<BoxRecord>>
            ) {
                val apiResult = response.body()
                if (apiResult?.errno == ApiResult.SUCCESS) {
                    boxRecord = apiResult.data
                    initValues()
                } else {
                    Log.d(TAG, "error, ${apiResult?.errmsg}")
                }
            }

            override fun onFailure(call: Call<ApiResult<BoxRecord>>, t: Throwable) {
                t.printStackTrace()
            }
        })
    }
}